package com.example.demo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/header")
@RestController
public class HeaderController {
    //传统获取cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie ck:cookies){
                System.out.println(ck.getName()+":"+ck.getValue());
            }
        }
        return "获取cookie成功";
    }


    //Session的存储
    //从cookie中获取SessionID,根据SessionID获得Session对象
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute("username", "雨木");
            session.setAttribute("age", 22);
        }
        return "session设置成功";
    }

    //Session的读取（方法一）
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        //默认就是true，可省略不写
        HttpSession session = request.getSession(true);
        //session类似于map结构
        String username = (String) session.getAttribute("username");
        System.out.println(session.getAttribute("age"));
        return "从session中获得username："+username;
    }

    //方法二 如果有session对象就返回，没有就创建
    @RequestMapping("getSession2")
    public String getSession(HttpSession session){
        String username=(String)session.getAttribute("username");
        return"获得username："+username;
    }

    //方法三
    @RequestMapping("getSession3")
    public String getSession(@SessionAttribute String username){
        return"获得username："+username;
    }

    //获取header
    @RequestMapping("getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("user-Agent");
        return userAgent;
    }

    //获取1header第二种方法
    @RequestMapping("gatHeader2")
    public String getHeader(@RequestHeader String userAgent){
        return "userAgent"+userAgent;
    }



}
